<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const messages = ref<Array<{ content: string; timestamp: string; is_customer: boolean }>>([])
const newMessage = ref('')
let ws: WebSocket | null = null

onMounted(async () => {
    if (!userStore.username) {
        ElMessage.error('请先登录')
        router.push('/chat') // 跳转到登录页面
        return
    }

    try {
        // 发送 JSON 请求
        const { data } = await axios.post(`http://127.0.0.1:8000/api/customer_service/login/`, {
            username: userStore.username, // 使用 JSON 格式发送 username
        })
        messages.value = data.messages || [] // 加载历史消息（如适用）
        initWebSocket()
    } catch (error) {
        console.error(error)
        ElMessage.error('获取聊天记录失败')
    }
})

onUnmounted(() => {
    ws?.close()
})

// 初始化 WebSocket
function initWebSocket() {
    ws = new WebSocket(`ws://127.0.0.1:8000/ws/chat/${userStore.uuid}/`)

    ws.onmessage = (event) => {
        const data = JSON.parse(event.data)
        messages.value.push({
            content: data.message,
            timestamp: new Date().toISOString(),
            is_customer: data.is_customer,
        })
    }

    ws.onclose = () => {
        console.log('WebSocket连接已关闭')
    }
}

// 发送消息
function sendMessage() {
    if (!newMessage.value.trim()) return

    ws?.send(
        JSON.stringify({
            message: newMessage.value,
        })
    )

    newMessage.value = ''
}
</script>

<template>
    <div class="chat-container">
        <div class="chat-header">
            <h2>在线咨询</h2>
            <el-button @click="router.push('/')">返回首页</el-button>
        </div>

        <div class="chat-messages" ref="messagesContainer">
            <div v-for="(msg, index) in messages" :key="index"
                :class="['message', msg.is_customer ? 'customer' : 'user']">
                <div class="message-content">
                    {{ msg.content }}
                </div>
                <div class="message-time">
                    {{ new Date(msg.timestamp).toLocaleString() }}
                </div>
            </div>
        </div>

        <div class="chat-input">
            <el-input v-model="newMessage" placeholder="请输入消息" @keyup.enter="sendMessage">
                <template #append>
                    <el-button @click="sendMessage">发送</el-button>
                </template>
            </el-input>
        </div>
    </div>
</template>

<style scoped>
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    padding: 1rem;
    background: #f9f9f9;

    .chat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
        background-color: #42b983;
        color: white;
        padding: 10px;
        border-radius: 5px;
    }

    .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: 1rem;
        background: #ffffff;
        border-radius: 4px;
        margin-bottom: 1rem;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

        .message {
            display: flex;
            flex-direction: column;
            margin-bottom: 1rem;
            max-width: 70%;
            word-wrap: break-word;

            &.user {
                align-self: flex-end;
                /* 用户消息在右侧 */
                text-align: right;

                .message-content {
                    background: #95ec69;
                    color: white;
                    border-radius: 10px 10px 0 10px;
                    padding: 0.5rem 1rem;
                }
            }

            &.customer {
                align-self: flex-start;
                /* 客服消息在左侧 */
                text-align: left;

                .message-content {
                    background: #f1f1f1;
                    color: black;
                    border-radius: 10px 10px 10px 0;
                    padding: 0.5rem 1rem;
                }
            }

            .message-time {
                font-size: 0.8rem;
                color: #999;
                margin-top: 0.2rem;
                margin-left: 10px;
                margin-right: 10px;
            }
        }
    }

    .chat-input {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 1rem 0;

        el-input {
            flex: 1;
        }

        el-button {
            background-color: #42b983;
            color: white;
        }

        el-button:hover {
            background-color: #369870;
        }
    }
}


</style>
